package com.wallpaper.weatherwallpaper;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.util.EncodingUtils;

import com.model.User;

import dalvik.system.VMRuntime;

import android.os.Bundle;
import android.os.Parcelable;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {
	// ViewPager��google SDk���Դ��һ�����Ӱ��һ���࣬��������ʵ����Ļ����л���
	// android-support-v4.jar
	private ViewPager mPager;//ҳ������
	private List<View> listViews; // Tabҳ���б�
	private ImageView cursor;// ����ͼ���ͼƬ
	private TextView systemWallPaperTextView, userWallPaperTextView;// ҳ��ͷ��
	private int offset = 0;// ����ͼ��ͼƬƫ����
	private int currIndex = 0;// ��ǰҳ�����
	private int bmpW;// ����ͼ��ͼƬ���	
	
	//By GY
	private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ;   
	private SystemImageAdapter systemImageAdapter;
	private GridView systemwallpaperGridview;
	private UserImageAdapter userImageAdapter;
	private GridView userwallpaperGridview;
	private Button addUserWallPaperButton;
	private String weather;
	private String time;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	//By GY
    	System.gc();//优化内存溢出
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //By GY
        VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE); //设置最小heap内存为6MB大小。（优化内存溢出）
        Bundle bundle=this.getIntent().getExtras();
        if(bundle!=null){
        	weather=bundle.getString("Weather");
            time=bundle.getString("Time");
        }
          
        User.getUser(MainActivity.this);
        
        InitImageView();
		InitTextView();
		InitViewPager();
		
		//By GY
		InitSystemwallpaperGridview();
		InitUserwallpaperGridview();
    }
    
    //By GY
    private void InitUserwallpaperGridview() {
    	addUserWallPaperButton=(Button)listViews.get(1).findViewById(R.id.AddUserWallPaperButton);
    	addUserWallPaperButton.setOnClickListener(new OnClickListener(){

			public void onClick(View v) {
				Intent intent=new Intent();
				intent.setClass(MainActivity.this, AddPictureActivity.class);
				startActivity(intent);
			}
    		
    	});
    	
		userwallpaperGridview=(GridView)listViews.get(1).findViewById(R.id.userPicturesGridview);
		userImageAdapter=new UserImageAdapter(MainActivity.this,getUserWallpaper());
		userwallpaperGridview.setAdapter(userImageAdapter);
		userwallpaperGridview.setOnItemClickListener(new OnItemClickListener(){
			//点击每张图片的事件，转到查看并设置当前图片为某天气时间对应壁纸
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				// TODO Auto-generated method stub
				Intent intent=new Intent();
				intent.setClass(MainActivity.this,ViewWallPaperActivity.class);
				Bundle bundle=new Bundle();
				bundle.putString("Weather", weather);
				bundle.putString("Time", time);
				bundle.putInt("pathInt", 0);
				bundle.putString("pathStr", userImageAdapter.getUserwallpaperPaths().get(position));
				intent.putExtras(bundle);
				startActivity(intent);
			}
			
		});
    	
	}

    //By GY
	private List<String> getUserWallpaper() {
		// TODO Auto-generated method stub
		List<String> userwallpaperPaths=new ArrayList<String>();
		String fileContent="";
		try {
			FileInputStream inStream=MainActivity.this.openFileInput("userwallpaper_path.txt");
			int length=inStream.available();
			byte[] buffer=new byte[length];
			inStream.read(buffer);
			fileContent=EncodingUtils.getString(buffer, "UTF-8");
			inStream.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String[] paths=fileContent.split("\\*");
		for(int i=0;i<paths.length;i++){
			userwallpaperPaths.add(paths[i]);
		}
		return userwallpaperPaths;
	}

	//By GY
    private void InitSystemwallpaperGridview() {
    	systemwallpaperGridview=(GridView)listViews.get(0).findViewById(R.id.systemPicturesGridview);
    	systemImageAdapter=new SystemImageAdapter(MainActivity.this,getSystemWallpaper()); 
    	systemwallpaperGridview.setAdapter(systemImageAdapter);
    	systemwallpaperGridview.setOnItemClickListener(new OnItemClickListener(){
    		//点击每张图片的事件，转到查看并设置当前图片为某天气时间对应壁纸
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				// TODO Auto-generated method stub
				Intent intent=new Intent();
				intent.setClass(MainActivity.this,ViewWallPaperActivity.class);
				Bundle bundle=new Bundle();
				bundle.putString("Weather", weather);
				bundle.putString("Time", time);
				bundle.putInt("pathInt", systemImageAdapter.getSystemwallpaperIds()[position]);
				bundle.putString("pathStr", null);
				intent.putExtras(bundle);
				startActivity(intent);
			}
    		
    	});
    	
	}

    //By GY
	private Integer[] getSystemWallpaper() {
		Integer[] systemwallpaper={
				R.drawable.cloudy, 
				R.drawable.lighting, 
				R.drawable.moon,
				R.drawable.rainy,
				R.drawable.snow,
				R.drawable.snow2,
				R.drawable.sunny,
				R.drawable.sunny2,
				R.drawable.bysea,
				R.drawable.sunny3,
				R.drawable.sunset,
				R.drawable.windy,
				R.drawable.windy2,
				};
		return systemwallpaper;
	}

	//当重新回到MainActivity的时候，刷新页面
    public void onResume(){
    	super.onResume();
     	//By GY
     	InitUserwallpaperGridview();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.activity_main, menu);
    	menu.add(0,1,1,"设置");
    	menu.add(0,2,2,"帮助");
        return true;
    }
    
    /**
	 * ��ʼ��ͷ��
	 */
	private void InitTextView() {
		systemWallPaperTextView = (TextView) findViewById(R.id.SystemWallPaperTextView);
		userWallPaperTextView = (TextView) findViewById(R.id.UserWallPaperTextView);

		systemWallPaperTextView.setOnClickListener(new MyOnClickListener(0));
		userWallPaperTextView.setOnClickListener(new MyOnClickListener(1));
	}

	/**
	 * ��ʼ��ViewPager
	 */
	private void InitViewPager() {
		mPager = (ViewPager) findViewById(R.id.vPager);
		listViews = new ArrayList<View>();
		LayoutInflater mInflater = getLayoutInflater();
		listViews.add(mInflater.inflate(R.layout.systemwallpaper, null));
		listViews.add(mInflater.inflate(R.layout.userwallpaper, null));
		mPager.setAdapter(new MyPagerAdapter(listViews));
		mPager.setCurrentItem(0);
		mPager.setOnPageChangeListener(new MyOnPageChangeListener());
	}

	/**
	 * ��ʼ������
	 */
	private void InitImageView() {
		cursor = (ImageView) findViewById(R.id.CursorImageView);
		bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.a)
				.getWidth();// ��ȡͼƬ���
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW = dm.widthPixels;// ��ȡ�ֱ��ʿ��
		offset = (screenW / 2 - bmpW) / 2;// ����ƫ����
		Matrix matrix = new Matrix();
		matrix.postTranslate(offset, 0);
		cursor.setImageMatrix(matrix);// ���ö�����ʼλ��
	}
	/**
	 * ViewPager������
	 */
	public class MyPagerAdapter extends PagerAdapter {
		public List<View> mListViews;

		public MyPagerAdapter(List<View> mListViews) {
			this.mListViews = mListViews;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(mListViews.get(arg1));
		}

		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public int getCount() {
			return mListViews.size();
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(mListViews.get(arg1), 0);
			return mListViews.get(arg1);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == (arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}
	}

	/**
	 * ͷ��������
	 */
	public class MyOnClickListener implements View.OnClickListener {
		private int index = 0;

		public MyOnClickListener(int i) {
			index = i;
		}

		public void onClick(View v) {
			mPager.setCurrentItem(index);
		}
	};

	/**
	 * ҳ���л�����
	 */
	public class MyOnPageChangeListener implements OnPageChangeListener {

		int one = offset * 2 + bmpW;// ҳ��1 -> ҳ��2 ƫ����
		int two = one * 2;// ҳ��1 -> ҳ��3 ƫ����

		public void onPageSelected(int arg0) {
			Animation animation = null;
			switch (arg0) {
			case 0:
				if (currIndex == 1) {
					animation = new TranslateAnimation(one, 0, 0, 0);
				} else if (currIndex == 2) {
					animation = new TranslateAnimation(two, 0, 0, 0);
				}
				break;
			case 1:
				if (currIndex == 0) {
					animation = new TranslateAnimation(offset, one, 0, 0);
				} else if (currIndex == 2) {
					animation = new TranslateAnimation(two, one, 0, 0);
				}
				break;
			case 2:
				if (currIndex == 0) {
					animation = new TranslateAnimation(offset, two, 0, 0);
				} else if (currIndex == 1) {
					animation = new TranslateAnimation(one, two, 0, 0);
				}
				break;
			}
			currIndex = arg0;
			animation.setFillAfter(true);// True:ͼƬͣ�ڶ�������λ��
			animation.setDuration(300);
			cursor.startAnimation(animation);
		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		public void onPageScrollStateChanged(int arg0) {
		}
	}
	
	/**
	 * Ϊ�˵�ѡ����ӵ���¼���
	 * ��������á�֮����ת������ҳ��
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// ��ת������ҳ��	
		//点击的是设置
		if(item.getItemId()==1){
			Intent intent = new Intent();
			intent.setClass(MainActivity.this, SettingActivity.class);
			startActivity(intent);
		}
		//点击的是帮助
		else if(item.getItemId()==2){
			AlertDialog.Builder builder = new Builder(MainActivity.this);
			String alertMessage = "    天气壁纸是一款基于天气更换壁纸的应用。"+"\n"
				+"    根据用户设置的所在城市，每隔一段时间获得当前天气信息，再依据不同的天气更换壁纸，白天和夜晚的壁纸也不相同。"+"\n"
				+"    用户可以设置获取天气的时间间隔，也可以设置不同天气不同时间的壁纸，壁纸可来源于应用提供的图库，也可来源于系统SD卡下的用户图库。"+"\n\n"
				+"    :)由于时间紧迫，第一阶段的功能有限，也可能存在一些漏洞，我们会在第二阶段中增加设置屏保等功能，也会在用户体验、数据安全性等方面有所加强。感谢大家对此款应用的支持，也欢迎您多提宝贵意见，并向我们反映使用过程中遇到的各种问题。"+"\n"
				+"    团队邮箱：weatherwp@163.com"+"\n\n";
			builder.setMessage(alertMessage);
			builder.setTitle("提示");
			builder.setPositiveButton("确定", new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			builder.create().show();
		}
		return false;
	}
	
	
	//By GY
	@Override
	public void onStop(){
		System.gc();//优化内存溢出
		super.onStop();
	}
}
